<?php
/*
* $Author ：PHPYUN开发团队
*
* 官网: http://www.phpyun.com
*
* 版权所有 2009-2019 宿迁鑫潮信息技术有限公司，并保留所有权利。
*
* 软件声明：未经授权前提下，不得用于商业运营、二次开发以及任何形式的再次发布。
 */
class crm_model extends model{
    /**
     * @desc   引用cache类
     */
    private function getCache($whereData = array()) {
        require_once ('cache.model.php');
        $CacheM = new cache_model($this->db, $this->def);
		
        return  $CacheM -> GetCache($whereData); 
    }
    
    /**
     * @desc 新增业务员任务
     * @param array $data
     */
    public function addWaitingTask($data = array()) {
        
        if (!empty($data)) {
            
            if(empty($data['auid']) || empty($data['uid']) || empty($data['comid'])){
                $return = array(
                    'errcoder'  =>  8,
                    'msg'       =>  '参数错误，请重试！'
                );
            }
            
            if (empty($data['type'])) {
                $return = array(
                    'errcoder'  =>  8,
                    'msg'       =>  '请选择任务类型！'
                );
            }
            
            if (empty($data['stime']) && $data['type']=="22") {
                $return = array(
                    'errcoder'  =>  8,
                    'msg'       =>  '请填写任务时间！'
                );
            }
            
            if (empty($data['content'])) {
                $return = array(
                    'errcoder'  =>  8,
                    'msg'       =>  '请填写任务描述！'
                );
            }
            
            $auid   =   intval($data['auid']);
            $uid    =   intval($data['uid']);
            $comid  =   intval($data['comid']);
            
            $value  =   array(
                
                'auid'      =>  $auid,
                'uid'       =>  $uid,
                'comid'     =>  $comid,
                'type'      =>  intval($data['type']),
                'content'   =>  $data['content'],
                'ctime'     =>  time(),
                'status'    =>  '1',
            );
            if($data['stime']){
				$value['stime']	=	$data['stime'];
			}
            $return['id']       =   $this->insert_into('crm_work_plan', $value);
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $return['id'] ? '成功' : '失败';
            $return['msg']      =   '任务新建'.$msg;
            
            return $return;
        }
    }
    
    /**
     * @desc  查询任务数量
     */
    function getTaskNum($whereData = array()) {

        return $this -> select_num('crm_work_plan', $whereData);
        
    }
    
    /**
     * @desc 查询任务记录
     */
    function  getTaskInfo($where = array(), $data = array()) {
        
        $select	=   $data['field'] ? $data['field'] : '*';
        
        $Info	=   $this -> select_once('crm_work_plan', $where, $select);
        if($Info['stime']){
			$Info['stime_n']   =  date('Y-m-d H:m:s',$Info['stime']);
		}
        return $Info;
        
    }
    
    
    /**
     * @desc 查询任务记录
     */
    function  getTaskList($where = array(), $data = array()) {
        
        $select     =   $data['field'] ? $data['field'] : '*';
        
        $taskList   =   $this -> select_all('crm_work_plan', $where, $select);
        
        if (!empty($taskList) && isset($data['utype']) && $data['utype'] == 'crm') {
            
            foreach ($taskList as $value){
                
                $comids[]   =   $value['comid'];
                $uids[]     =   $value['uid'];
				$auids[]     =   $value['auid'];
                
            }
            require_once 'company.model.php';
            $companyM	=	new company_model($this->db, $this->def);
            $list		=	$companyM -> getList(array('uid' => array('in', pylode(',', $comids))),array('field' => '`uid`, `name`'));
			$list		=	$list['list'];
            
            $users      =   $this -> select_all('admin_user', array('uid' => array('in', pylode(',', $uids))), '`uid`,`name`');
            $ausers     =   $this -> select_all('admin_user', array('uid' => array('in', pylode(',', $auids))), '`uid`,`name`');
			
			$weekarray=array('日','一','二','三','四','五','六');
			
            foreach ($taskList as $k => $v){
                
				if($v['stime']!=''){
				    
					$stime		=	date('n月j日',$v['stime']).'(周'.$weekarray[date("w",$v['stime'])].')'.date('G点',$v['stime']);
					$sfen		=	intval(date('i',$v['stime']));
					
					if($sfen){
						$stime	.=	$sfen.'分';
					}else{
						$stime	.=	'整';
					}
					
					$taskList[$k]['stime_n']   =   $stime;
					
					if ($v['stime'] >= strtotime(date('Y-m-d'))) {
					    
					    $taskList[$k]['taskDay']    =   format_datetime($v['stime'], 2, 2, '');
					}else{
					    $taskList[$k]['taskDay']    =   format_datetime($v['stime'], 2, 1, '');
					}
					
				}
				
				if($v['ctime']){
					$ctime		=	date('n月j日',$v['ctime']).'(周'.$weekarray[date("w",$v['ctime'])].')'.date('G点',$v['ctime']);
					$cfen		=	intval(date('i',$v['ctime']));
					if($cfen){
						$ctime	.=	$cfen.'分';
					}else{
						$ctime	.=	'整';
					}
					$taskList[$k]['ctime_n']   =   $ctime;
					
					if ($v['ctime'] >= strtotime(date('Y-m-d'))) {
					    $taskList[$k]['addDay']    =   format_datetime($v['ctime'], 2, 2, '');
					}else{
					    $taskList[$k]['addDay']    =   format_datetime($v['ctime'], 2, 1, '');
					}
					
				}
                foreach ($list as $uv){
                    
                    if ($v['comid'] == $uv['uid']) {
                        $taskList[$k]['name']   =   $uv['name'];
                    }
                }
				foreach ($users as $av){
                    
                    if ($v['uid'] == $av['uid']) {
                        $taskList[$k]['cname']   =   $av['name'];
                    }
                    if ($v['auid'] == $av['uid']) {
                        $taskList[$k]['aname']   =   $av['name'];
                    }
                }
                foreach ($ausers as $av){
					
                    if ($v['auid'] == $av['uid']) {
                        $taskList[$k]['uname']   =   $av['name'];
                    }
                }
            }
        }
        return $taskList;
    }
    /**
     * @desc 更新任务
     */
    function  upTask($data = array(), $where = array()) {
		
        return  $this -> update_once('crm_work_plan', $data, $where);
    }
     /**
     * @desc 删除任务
     */
    function  delTask($where = array()) {
        return  $this -> delete_all('crm_work_plan', $where,'');
    }
    /**
     * @desc    新增业务员跟进记录
     * @param   array $data
     */
    public function addConcern($data = array()) {
        
        if (!empty($data)) {
            
            $value  =   array(
                
                'uid'       =>  intval($data['uid']),
                'comid'     =>  intval($data['comid']),
                'time'      =>  strtotime($data['time']),
                'type'      =>  intval($data['type']),
                'content'   =>  $data['content'],
                'status'    =>  intval($data['status']),
                'note'      =>  $data['note'],
                'atime'     =>  time()
            );
            
            $nid    =   $this -> insert_into('crmnew_concern', $value);
            
            if ($nid) {
                $this->update_once('company', array('isfollow' => 1), array('uid' => $data['comid']));
            }
            
            return  $nid;
            
        }
        
    }
    
    /**
     * @desc  查询跟进记录数量
     */
    function getConcernNum($whereData = array()) {
        
        return $this -> select_num('crmnew_concern', $whereData);
        
    }
    
    /**
     * @desc 查询跟进记录
     */
    function getConcernInfo($where = array(), $data = array()){
        
        $select         =   $data['field'] ? $data['field'] : '*';
        
        $concernInfo    =   $this -> select_once('crmnew_concern', $where, $select);
        
        return $concernInfo;
        
    }
    
    /**
     * @desc 查询跟进记录
     */
    function getConcernList($where = array(), $data = array()){
        
        $select         =   $data['field'] ? $data['field'] : '*';
       
        $concernList    =   $this -> select_all('crmnew_concern', $where, $select);
       
        if (!empty($concernList)) {
            
			if(isset($data['utype']) && $data['utype'] == 'crm'){
			    
			    $cache      =   $this -> GetCache(array('crm'));
				
			    $comids  =   $auids  =   array();
			    
				foreach ($concernList as $value){
					
					$comids[]   =   $value['uid'];
					$auids[]    =   $value['auid'];
				}
				
				$comList    =   $this->select_all('company', array('uid' => array('in', pylode(',', $comids))),'`uid`,`name`, `linkman`,`linktel`');
				
				$ausers     =   $this->select_all('admin_user', array('uid' => array('in', pylode(',', $auids))),'`uid`,`name`');
				 
				
				foreach ($concernList as $k => $v){
				    
					if($v['type']){
						$concernList[$k]['type_n']=$cache['crmclass_name'][$v['type']];
					}
					
					if($v['status']){
						$concernList[$k]['status_n']=$cache['crmclass_name'][$v['status']];
					}
					
					foreach ($comList as $cv){
						
						if ($v['uid'] == $cv['uid']) {
							$concernList[$k]['name']    =   $cv['name'];
							$concernList[$k]['linkman'] =   $cv['linkman'];
							$concernList[$k]['moblie']  =   $cv['linktel'];
						}
					}
					foreach ($ausers as $av){
						
						if ($v['auid'] == $av['uid']) {
							$concernList[$k]['aname']   =   $av['name'];
						}
					}
					
					if ($v['atime'] > strtotime(date('Y-m-d'))) {
					    $concernList[$k]['isup']   =   1;
					}
				}
			}
            
        }
        
        return $concernList;
        
    }

	/**
	 * @desc	删除跟进记录
     */
	public function delConcern($delId){
		
		if(empty($delId)){
           
			$return	 =   array(
              
			  'errcode' => 8,
               
			  'msg' 	=> '请选择要删除的数据！',                
            );
        
		}else{
			
			if(is_array($delId)){
				
				$delId	=	pylode(',',$delId);
				
				$return['layertype']	=	1;
			
			}else{
				
				$return['layertype']	=	0;
			}
 			
			$nid	=	$this -> delete_all('crmnew_concern',array('id' => array('in',$delId)),'');
			
			//  同步跟新任务数据关联的跟进记录ID
			if($nid){

				$this -> update_once('crm_work_plan', array('cid' => '0'), array('cid' => array('in', $delId)));

 			}
			
			$return['msg']		=	'跟进记录';
			
			$return['errcode']	=	$nid ? '9' :'8';
			
			$return['msg']		.=	$nid ? '删除成功！' : '删除失败！';
		 
		
		}
		
		return	$return;
		
	}
    
    /**
     * @desc CRM 业务员  新开通客户会员等级  订单记录
     * @param array $data
     */
    public function addDeal($data = array())
    {
        if (!empty($data)) {
            
            if (empty($data['uid']) || empty($data['auid'])) {
                
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '参数错误，请重试'
                );
            }
            
            if (empty($data['rating'])) {
                
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请选择会员套餐'
                );
            }else{
                
                $rating =   $this->select_once('company_rating', array('id' => intval($data['rating'])), '`name`');
                
                if (empty($rating)) {
                    
                    $return =   array(
                        'errcode'   =>  8,
                        'msg'       =>  '请选择正确的会员套餐'
                    );
                }
            }
            
            if (empty($data['order_type'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请选择支付方式'
                );
            }
            
            if (!empty($return)) {
                
                return $return;
            }
            
            
            $uid    =   intval($data['uid']);
            $auid   =   intval($data['auid']);
            
            if (!empty($data['order_price']) && round($data['order_price'], 2) > 0) {
                
                if (empty($data['id'])) {
                    $dingdan    =   time().rand(10000, 99999);
                    $orderData  =   array(
                        'uid'           =>  $uid,
                        'order_id'      =>  $dingdan,
                        'order_type'    =>  $data['order_type'],
                        'order_price'   =>  round($data['order_price'], 2),
                        'order_time'    =>  time(),
                        'order_state'   =>  '1',
                        'order_remark'  =>  $data['order_remark'],
                        'type'          =>  1,
                        'rating'        =>  $data['rating'],
                        'crm_uid'       =>  $auid,
                        'usertype'      =>  2,
                        'did'           =>  $this->config['did']
                    );
                    
                    $return['id']       =   $this->insert_into('company_order', $orderData);
                }else{
                    
                    $orderData  =   array(
                        
                        'order_type'    =>  $data['order_type'],
                        'order_price'   =>  round($data['order_price'], 2),
                        'order_time'    =>  time(),
                        'order_remark'  =>  $data['order_remark'],
                        'rating'        =>  $data['rating']
                    );
                    
                    $return['id']       =   $this->update_once('company_order', $orderData, array('id' => $data['id']));
                }
                
                
                
                
                if ($return['id'] && empty($data['id'])) {  //  需改订单，不记录
                    
                    $logData    =   array(
                        'auid'      =>  $auid,
                        'uid'       =>  $uid,
                        'type'      =>  8,
                        'content'   =>  '开通会员【'.$rating['name'].'】, 录入订单【'.$dingdan.'】',
                        'remark'    =>  $data['order_remark'],
                        'ctime'     =>  time()
                    );
                    
                    $this->addCrmComLog($logData);
                }
                
                $return['errcode']  =   $return['id'] ? 9 : 8;
                $msg                =   $return['id'] ? '录入成功' : '录入失败，请重试！';
                $return['msg']      =   '客户订单'.$msg;
                
                return $return;
            }
        }
    }
    
    /**
     * @desc 查询数据，返回工作台简报数目
     */
    function getWorkReport($data = array()) {
        
        if (!empty($data)) {
            
            $return =   array();
             
            $sdate  =   $data['sdate'];
            $edate  =   $data['edate'];
            $auid   =   intval($data['auid']);
            
            $timeArr    =   array(
                
                '0'  =>  array('>', $sdate, 'AND'),
                '1'  =>  array('<', $edate, 'AND')
                
            );
            
            $comWhere   =   array(
              
                'crm_time'  =>  $timeArr,
                'crm_uid'   =>  $auid
                
            );
            
            $return['khNum']    =   $this -> select_num('company', $comWhere);
            
            
            $concernWhere   =  array(
                
                'time'  =>  $timeArr,
                'uid'   =>  $auid
                
            );
            
            $return['followNum']    =   $this -> select_num('crmnew_concern', $concernWhere);
            
            $orderWhere     =   array(
              
                'order_time'    =>  $timeArr,
                'crm_uid'       =>  $auid,
                'order_price'   =>  array('>', 0),
                'order_state'   =>  2
                
            );
            
            $orderAll       =   $this -> select_all('company_order', $orderWhere, '`order_price`');

            $ordersum       =   0;
            foreach($orderAll as $v){
                $ordersum   +=  $v['order_price'];
            }
            if($ordersum > 0){
                $return['orderDealPrice']   =	floatval($ordersum);
            }else{
                $return['orderDealPrice']   =	0;
            }

            $return['orderNum']     =   $this -> select_num('company_order', $orderWhere);
            
            return $return;
            
        }
        
    }
    /**
     * @desc    获取crm工作日志列表
     * @param   array $whereData
     * @param   array $data
     */
    public function getWorkLogList($where=array(),$data=array()){
        
        $field  =  $data['field'] ? $data['field'] : '*';

        $List  =  $this -> select_all('crm_work_log',$where,$field);
        if (!empty($List)) {
            foreach ($List as $v){
                $auids[]    =   $v['auid'];
            }
            $users =   $this->select_all('admin_user', array('uid' => array('in', pylode(',', $auids))),'`uid`,`name`');
            foreach ($List as $k => $v){
                foreach ($users as $val){
                    if ($v['auid'] == $val['uid']) {
                        $List[$k]['name']   =   $val['name'];
                    }
                } 
            }
        }
        return	$List;
    }
    /**
     * @desc    新增工作日志
     * @param array $data
     */
    public function addWorkLog($data = array()){
       
        if (!empty($data)) {
            $return =   array();
            $value  =   array(
                'auid'      =>  intval($data['auid']),
                'title'     =>  trim($data['title']),
                'content'   =>  $data['content'],
                'ctime'     =>  time()
            );
            $return['id']   =   $this -> insert_into('crm_work_log', $value);
            if($return['id']){
                $return['errcode']  =   9;
                $return['msg']      =   '添加成功';
            }else{ 
                $return['errcode']  =   8;
                $return['msg']      =   '添加失败';
            }
            return $return;
        }
    }
    /**
     * @desc 查询任务记录
     */
    function  getWorkLogInfo($where = array(), $data = array()) {
        
        $select	=   $data['field'] ? $data['field'] : '*';
        
        $Info	=   $this -> select_once('crm_work_log', $where, $select);

        return $Info;
        
    }
    /**
	 * @desc	删除工作日志
     */
	public function delWorkLog($delId){
		
		if(empty($delId)){
           
			$return	 =   array(
              
			  'errcode' => 8,
               
			  'msg' 	=> '请选择要删除的数据！',                
            );
        
		}else{
			
			if(is_array($delId)){
				
				$delId	=	pylode(',',$delId);
				
				$return['layertype']	=	1;
			
			}else{
				
				$return['layertype']	=	0;
			}
 			
			$nid	=	$this -> delete_all('crm_work_log',array('id' => array('in',$delId)),'');

			$return['msg']		=	'工作日志';
			
			$return['errcode']	=	$nid ? '9' :'8';
			
			$return['msg']		.=	$nid ? '删除成功！' : '删除失败！';
		 
		
		}
		return	$return;
    }
    /**
     * @desc    获取外出申请列表
     * @param array $whereData
     * @param array $data
     */
    public function getOutList($where = array(), $data = array())
    {
        $field  =   $data['field'] ? $data['field'] : '*';
        
        $List   =   $this->select_all('crm_out', $where, $field);
        
        if (!empty($List)) {
            
            $uids   =   $comids =   array();
            
            foreach ($List as $v) {
                if ($v['auid'] && !in_array($v['auid'], $uids)) {
                    $uids[]     = $v['auid'];
                }
                if ($v['uid'] && !in_array($v['uid'], $comids)) {
                    $comids[]   = $v['uid'];
                }
            }

            $user   =   $this->select_all('admin_user', array('uid' => array('in', pylode(',', $uids))), '`uid`,`name`');
            
            $com    =   $this->select_all('company', array('uid' => array('in', pylode(',', $comids))), '`uid`,`name`,`linkman`,`linktel`');
            
            foreach ($List as $k => $v) {
            
                foreach ($user as $val) {
                    if ($v['auid'] == $val['uid']) {
                        $List[$k]['name'] = $val['name'];
                    }
                }
                
                foreach ($com as $value) {
                    if ($v['uid'] == $value['uid']) {
                        $List[$k]['comname'] = $value['name'];
                        $List[$k]['linkman'] = $value['linkman'];
                        $List[$k]['linktel'] = $value['linktel'];
                    }
                }
            }
        }
        return $List;
    }
    /**
     * @desc    新增外出申请
     * @param array $data
     */
    public function addOut($data = array()){
       
        if (!empty($data)) {
            
            $return =   array();
            
            $value  =   array(
                'auid'      =>  intval($data['auid']),
                'uid'       =>  intval($data['uid']),
                'reason'    =>  intval($data['reason']),
                'remark'    =>  $data['remark'],
                'stime'     =>  $data['stime'],
                'etime'     =>  $data['etime'],
                'status'    =>  1,
                'ctime'     =>  time()
            );
            
            $return['id']       =   $this -> insert_into('crm_out', $value);
             
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $return['id'] ? '成功' : '失败';
            $return['msg']      =   '添加外出申请'.$msg;
            
            return $return;
        }
    }
    
    /**
     * @desc    更新外出记录
     */
    function  upOut($data = array(), $where = array()) {
		
        return  $this -> update_once('crm_out', $data, $where);
    }
    /**
	 * @desc   删除工作日志
     */
	public function delOut($delId){
		
		if(empty($delId)){
           
			$return  =   array(
              
			  'errcode' => 8,
               
			  'msg' 	=> '请选择要删除的数据！',                
            );
        
		}else{
			
			if(is_array($delId)){
				
				$delId	=	pylode(',',$delId);
				
				$return['layertype']	=	1;
			
			}else{
				
				$return['layertype']	=	0;
			}
 			
			$nid	=	$this -> delete_all('crm_out',array('id' => array('in',$delId)),'');

			$return['msg']		=	'外出申请';
			
			$return['errcode']	=	$nid ? '9' :'8';
			
			$return['msg']		.=	$nid ? '取消成功！' : '取消失败！';
		 
		
		}
		return	$return;
    }
    
    /**
     * @desc CRM客户管理操作记录
     * @param array $data
     */
    function addCrmComLog($data = array()){
        if (!empty($data)) {
            
            $nid    =   $this -> insert_into('crm_comlog', $data);
            
            return $nid;
        }
    }
    
    /**
     * @desc 获取客户操作记录（顾问对客户的操作）
     * @param array $where
     * @param array $data
     */
    function getComLogList($where = array(), $data = array()){
        
        $field      =   $data['field'] ? $data['field'] : '*';

        $logList    =   array();
        
        if (!empty($where)) {
            
            $logList    =   $this->select_all('crm_comlog', $where, $field);
            
            $cache      =   $this -> GetCache(array('crm'));
            
            $comids  =   $auids  =   array();
            
            foreach ($logList as $value){
                
                $comids[]   =   $value['uid'];
                $auids[]    =   $value['auid'];
            }
            
            $comList    =   $this->select_all('company', array('uid' => array('in', pylode(',', $comids))),'`uid`,`name`, `linkman`,`linktel`');
            
            $ausers     =   $this->select_all('admin_user', array('uid' => array('in', pylode(',', $auids))),'`uid`,`name`');
            
            
            foreach ($logList as $k => $v){
                
                if($v['type'] == 1){
                    
                    $logList[$k]['type_n']  =   '【转交】 业务员：【】';
                    
                }else if($v['type'] == 2){
                    
                    $logList[$k]['type_n']  =   '【放弃】';
                    
                }else if($v['type'] == 3){
                    
                    $logList[$k]['type_n']  =   '【开通订单：金牌会员】';
                    
                }else if($v['type'] == 4){
                    
                    $logList[$k]['type_n']  =   '【跟进/访问】';
                    
                }else if($v['type'] == 5){
                    
                    $logList[$k]['type_n']  =   '【修改企业资料】';
                    
                }else if($v['type'] == 6){
                    
                    $logList[$k]['type_n']  =   '【修改联系方式】';
                    
                }else if($v['type'] == 7){
                    
                    $logList[$k]['type_n']  =   '【'.$v['content'].'】';
                }else if($v['type'] == 8){
                    
                    $logList[$k]['type_n']  =   '【最新反馈备注】';
                    
                }else if($v['type'] == 9){
                    
                    $logList[$k]['type_n']  =   $v['content'];
                }
                 
                foreach ($comList as $cv){
                    
                    if ($v['uid'] == $cv['uid']) {
                        $logList[$k]['name']    =   $cv['name'];
                        $logList[$k]['linkman'] =   $cv['linkman'];
                        $logList[$k]['moblie']  =   $cv['linktel'];
                    }
                }
                
                foreach ($ausers as $av){
                    
                    if ($v['auid'] == $av['uid']) {
                        $logList[$k]['aname']   =   $av['name'];
                    }
                }
            }
            
            
        }
        
        return $logList;
         
    }
    
    /**
     * @desc 转交客户
     * @param array $data|crm_uid 转移到顾问UID; uid 客户（企业）ID; auid 转移顾问本人UID
     */
    function deliverUser($data = array()){
        
        if (!empty($data)){

            if (empty($data['crm_uid'])) {
                 
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请选择转交客户顾问'
                );
                return $return;
            }
            
            if (empty($data['uid'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请选择需要转交的客户'
                );
                return $return;
            }
            
            $crm_uid    =   intval($data['crm_uid']);
            $crm_name   =   trim($data['crm_name']);
            
            $uid        =   explode(',', $data['uid']);
            
            $auid       =   intval($data['auid']);
            $remark     =   $data['remark'];

            $return['id']   =   $this->update_once('company', array('crm_uid' => $crm_uid), array('uid' => array('in', pylode(',', $uid))));
            
            if ($return['id']) {
                
                $logData    =   array();
                
                foreach ($uid as $k => $v){
                    $logData[$k]['auid']    =   $auid;
                    $logData[$k]['uid']     =   $v;
                    $logData[$k]['type']    =   1;
                    $logData[$k]['content'] =   '【售后转交客户】给【业务员：'.$crm_name.'】';
                    $logData[$k]['remark']  =   $remark;
                    $logData[$k]['ctime']   =   time();
                }
                
                $this->DB_insert_multi('crm_comlog', $logData);
                
                /* $logData = array(
                    'auid'      =>  $auid,
                    'uid'       =>  $uid,
                    'type'      =>  1,
                    'content'   =>  '【售后转交客户】给【业务员：'.$crm_name.'】',
                    'remark'    =>  $remark,
                    'ctime'     =>  time()
                ); 
                $this->addCrmComLog($logData);
                */
                
                
            }
            
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $return['id'] ? '成功' : '失败';
            $return['msg']      =   '客户转交'.$msg;
            
            return $return;
        }
    }
    
    /**
     * @desc 放弃客户
     * @param array $data|uid 客户（企业）ID; auid 操作人UID
     */
    function giveUpUser($data = array()){
        
        if (!empty($data)){
            
            if (empty($data['uid'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请选择需要放弃的客户'
                );
                return $return;
            }
            
            $uid        =   explode(',', $data['uid']);
            $auid       =   intval($data['auid']);
            $remark     =   $data['remark'];
            
            $return['id']   =   $this->update_once('company', array('crm_uid' => 0), array('uid' => array('in', pylode(',', $uid))));
            
            if ($return['id']) {
                
                $logData    =   array();
                
                foreach ($uid as $k => $v){
                    $logData[$k]['auid']    =   $auid;
                    $logData[$k]['uid']     =   $v;
                    $logData[$k]['type']    =   2;
                    $logData[$k]['content'] =   '【放弃客户】';
                    $logData[$k]['remark']  =   $remark;
                    $logData[$k]['ctime']   =   time();
                }
                
                $this->DB_insert_multi('crm_comlog', $logData);
                
               /*  $logData = array(
                    'auid'      =>  $auid,
                    'uid'       =>  $uid,
                    'type'      =>  2,
                    'content'   =>  '【放弃客户】',
                    'remark'    =>  $remark,
                    'ctime'     =>  time()
                );
                
                $this->addCrmComLog($logData); */
            }
            
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $return['id'] ? '成功' : '失败';
            $return['msg']      =   '放弃客户'.$msg;
            
            return $return;
        }
    }
    
    /**
     * @desc 修改客户状态/等级
     * @param array $data|uid 客户（企业）ID; auid 操作人UID; st 客户状态/等级ID st_n 状态/等级名称
     */
    function upComST($data = array()){
        
        if (!empty($data)){
            
            if (empty($data['st'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  $data['isSt'] == 'status' ? '请选择客户状态' : '请选择客户等级'
                );
                return $return;
            }
            
            if (empty($data['uid'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请选择需要修改等级的客户'
                );
                return $return;
            }
            
            $uid    =   explode(',', $data['uid']);
            
            $auid   =   intval($data['auid']);
            $st     =   intval($data['st']);
            $st_n   =   $data['st_n'];
            $remark =   $data['remark'];

            $value  =   $data['isSt'] == 'status' ? array('crm_status' => $st) : array('crm_type' => $st);
            
            $return['id']   =   $this->update_once('company', $value, array('uid' => array('in', pylode(',', $uid))));
            
            if ($return['id']) {
                
                $logData    =   array();
                
                $type       =   $data['isSt'] == 'status' ? 9 : 7;
                $content    =   $data['isSt'] == 'status' ? '【修改客户状态】为：【'.$st_n.'】' : '【标记客户等级】为：【'.$st_n.'】';
                
                foreach ($uid as $k => $v){
                    $logData[$k]['auid']    =   $auid;
                    $logData[$k]['uid']     =   $v;
                    $logData[$k]['type']    =   $type;
                    $logData[$k]['content'] =   $content;
                    $logData[$k]['remark']  =   $remark;
                    $logData[$k]['ctime']   =   time();
                }
                
                $this->DB_insert_multi('crm_comlog', $logData);
                
                /* $logData = array(
                    'auid'      =>  $auid,
                    'uid'       =>  $uid,
                    'type'      =>  $data['isSt'] == 'status' ? 9 : 7,
                    'content'   =>  $data['isSt'] == 'status' ? '【修改客户状态】为：【'.$st_n.'】' : '【标记客户等级】为：【'.$st_n.'】',
                    'remark'    =>  $remark,
                    'ctime'     =>  time()
                );
                
                $this->addCrmComLog($logData); */
            }
            
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $data['isSt'] == 'status' ?'客户状态修改' : '客户等级修改';
            $msg                .=   $return['id'] ? '成功' : '失败';
            $return['msg']      =   $msg;
            
            return $return;
        }
    }
    
    /**
     * @desc 客户管理 -> 联系跟进记录添加
     * @param array $data|uid 客户（企业）ID; auid 操作人UID;
     */
    function addFollow($data = array()){
        
        if (!empty($data)){
            
            if (empty($data['uid'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '参数错误，请重试！'
                );
                return $return;
            }
            
            if (empty($data['type'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请选择跟进方式！'
                );
                return $return;
            }
            
            if (empty($data['remark'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请填写跟进描述！'
                );
                return $return;
            }
            
            require_once 'company.model.php';
            $comM   =   new company_model($this->db, $this->def);
            $uid    =   intval($data['uid']);
            $comInfo=   $comM -> getInfo($uid, array('field' => '`uid`, `crm_uid`'));
            
            $auid   =   intval($data['auid']);
            
            if ($auid != $comInfo['crm_uid']) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '非自己客户，暂无权限添加跟进！'
                );
                return $return;
            }
            
            if (!empty($data['crmtid'])) {  // 完成任务，添加跟进反馈说明
                
                $data['remark'] =   '完成任务，添加跟进反馈：'.$data['remark'];
            }
            
            $value      =   array(
                
                'uid'       =>  $uid,
                'auid'      =>  $auid,
                'time'      =>  strtotime($data['ftime']),
                'type'      =>  intval($data['type']),
                'content'   =>  $data['remark'],
                'atime'     =>  time()
            );
            
            if ($data['follow'] == 1 && !empty($data['ftime'])) {
                
                if (strtotime($data['ftime']) < time()) {
                    $return =   array(
                        'errcode'   =>  8,
                        'msg'       =>  '跟进时间需在当前时间之后！'
                    );
                    return $return;
                }
                
                $taskValue  =   array(
                    
                    'auid'      =>  $auid,
                    'uid'       =>  $auid,
                    'comid'     =>  $uid,
                    'type'      =>  22, //  跟进任务类型字段  值22 跟进任务 
                    'content'   =>  $data['remark'].'；需要进一步跟进【'.$data['ftime'].'】',
                    'stime'     =>  strtotime($data['ftime']),
                    'ctime'     =>  time(),
                    'status'    =>  '1'
                );
            } 
            
            if ($data['id']) {  // 修改跟进
                
                $return['id']   =   $this -> update_once('crmnew_concern', $value, array('id' => intval($data['id'])));
                
                if(empty($data['taskid'])){
                    
                    $taskValue['cid']   =   intval($data['id']);
                    
                    $arr    =   $this -> addWaitingTask($taskValue);
                    
                    if ($arr['id']) {
                    
                        $this->update_once('crmnew_concern', array('taskid' => $arr['id']), array('id' => intval($data['id'])));
                    }
                    
                }else{
                    
                    $this -> upTask($taskValue, array('id' => intval($data['taskid'])));
                }
            }else{  // 新增跟进
                
                $return['id']   =   $this -> insert_into('crmnew_concern', $value);
                
                if(!empty($taskValue)){
                    
                    $taskValue['cid']   =   $return['id'];
                    
                    $arr    =   $this -> addWaitingTask($taskValue);
                    
                    if ($arr['id']) {
                        
                        $this->update_once('crmnew_concern', array('taskid' => $arr['id']), array('id' => $return['id']));
                    }
                }elseif (!empty($data['crmtid'])){
                    
                     $this->upTask(array('status' => 2, 'etime' => time()), array('id' => $data['crmtid']));
                }
            }
            
            if ($return['id']) {
                
                $logData    =   array(
                    'auid'      =>  intval($data['auid']),
                    'uid'       =>  $uid,
                    'type'      =>  4,
                    'content'   =>  $data['id'] ? '【修改跟进计划】'  : '【添加跟进计划】',
                    'remark'    =>  $data['remark'],
                    'ctime'     =>  time()
                );
                
                $this->addCrmComLog($logData);
                
                if(!empty($data['crmtid'])){
                    $this->upTask(array('status' => 2));
                }
                
                $this->update_once('company', array('isfollow' => 1), array('uid' => $uid));
            }
            
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $data['id'] ? '修改' : '添加';
            $msg                .=   $return['id'] ? '成功' : '失败';
            $return['msg']      =   '客户跟进'.$msg;
            
            return $return;
        }
    }
    
    /**
     * @desc 修改客户联系方式
     * @param array $data|uid 客户（企业）ID; auid 操作人UID; 
     */
    function upComLink($data = array()){
        
        if (!empty($data)){
            
            if (empty($data['linktel'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '请填写客户联系手机'
                );
                return $return;
            }elseif(!CheckMoblie($data['linktel'])){
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '客户联系手机格式错误，请重新填写'
                );
                return $return;
            }
            
            if (!empty($data['linkphone']) && !CheckTell($data['linkphone'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '客户固话格式错误，请重新填写'
                );
                return $return;
            }
            
            if (!empty($data['linkmail']) && !CheckRegEmail($data['linkmail'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '客户邮箱格式错误，请重新填写'
                );
                return $return;
            }
            
            if (empty($data['uid'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '参数错误，请重试'
                );
                return $return;
            }
            
            $uid    =   intval($data['uid']);
            $auid   =   intval($data['auid']);
            
            $upData         =   array(
                'linkman'   =>  $data['linkman'],
                'linkjob'   =>  $data['linkjob'],
                'linktel'   => $data['linktel'], 
                'linkphone' => $data['linkphone'], 
                'linkmail'  => $data['linkmail']
            );
            $return['id']   =   $this -> update_once('company', $upData , array('uid' => $uid));
            
            if ($return['id']) {
                
                $logData = array(
                    'auid'      =>  $auid,
                    'uid'       =>  $uid,
                    'type'      =>  6,
                    'content'   =>  '【修改企业联系方式】',
                    'remark'    =>  '联系人：'.$data['linkman'].'，职称：'.$data['linkjob'].'，手机：'.$data['linktel'].'，固话：'.$data['linkphone'].'，邮箱：'.$data['linkmail'],
                    'ctime'     =>  time()
                );
                
                $this->addCrmComLog($logData);
            }
            
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $return['id'] ? '成功' : '失败';
            $return['msg']      =   '客户联系方式修改'.$msg;
            
            return $return;
        }
    }
    
    /**
     * @desc 联系反馈-》添加备注
     * @param array $data|uid 客户（企业）ID; auid 操作人UID;  
     */
    function remarkCom($data = array()){
        
        if (!empty($data)){
            
            if (empty($data['uid'])) {
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '参数错误，请重试！'
                );
                return $return;
            }
            
            $uid        =   intval($data['uid']);
            $auid       =   intval($data['auid']);
            $remark     =   $data['crm_remark'];
            
            $return['id']   =   $this->update_once('company', array('crm_remark' => $remark), array('uid' => $uid));
            
            if ($return['id']) {
                
                $logData = array(
                    'auid'      =>  $auid,
                    'uid'       =>  $uid,
                    'type'      =>  8,
                    'content'   =>  '【添加备注反馈】',
                    'remark'    =>  $remark,
                    'ctime'     =>  time()
                );
                
                $this->addCrmComLog($logData);
            }
            
            $return['errcode']  =   $return['id'] ? 9 : 8;
            $msg                =   $return['id'] ? '成功' : '失败';
            $return['msg']      =   '客户备注'.$msg;
            
            return $return;
        }
    }
    
    /**
     * @desc 获取短信模板
     * @param array $data: uid, auid, tp;
     */
     
    function getMsgTpl($data = array()){
        
        if (!empty($data)) {
            
            if (empty($data['uid']) || empty($data['auid']) || empty($data['tp'])) {
                
                $return =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '参数错误，请重试'   
                );
                
                return $return;
            }
            
            $uid    =   intval($data['uid']);
            $auid   =   intval($data['auid']);
            $tp     =   trim($data['tp']);
            
            $msgData=   array();
            
            $crm    =   $this->select_once('admin_user', array('uid' => $auid), '`name`,`moblie`');
            if (!empty($crm) && is_array($crm)) {
                $msgData['aname']   =   $crm['name'];
                $msgData['aphone']  =   $crm['moblie'];
            }
            
            if ($tp == 'crmreg') {
                
                $member     =   $this->select_once('member', array('uid' => $uid), '`username`');
                $msgData['username']    =   $member['username'];
            }
            
            $msgData['type']    =   $tp;
            
            require_once 'notice.model.php';
            $noticeM    =   new notice_model($this->db, $this->def);
            $msgTpl     =   $noticeM -> getTpl($msgData, 'msg');

            if ($msgTpl['status'] == '-1') {
                
                $return['errcode']  =   8;
                $return['msg']      =   $msgTpl['msg'];
                
            }else{
                $return['errcode']  =   9;
                $return['content']  =   $msgTpl['content'];
                $return['length']   =   mb_strlen($msgTpl['content'], 'UTF-8');
            }
            
            return  $return;
        }
        
    }
    
    /**
     * @desc    CRM管理客户，发送短信
     * @param array $data 
     */
    function sendCrmMsg($data = array()) {
        
        if (!empty($data)) {
            
            if (empty($data['uid']) || empty($data['auid']) || empty($data['tp']) || empty($data['mobile']) || empty($data['content'])) {
                
                $return  =   array(
                    'errcode'   =>  8,
                    'msg'       =>  '参数错误，请重试！'
                );
                return $return;
            }
            
            require_once 'notice.model.php';
            $noticeM    =   new notice_model($this->db, $this->def);
            
            $msgData    =   array(
                'mobile'    =>  $data['mobile'],
                'content'   =>  $data['content'],
                'uid'       =>  $data['uid'],
                'type'      =>  $data['tp']
            );
            
            $arr    =   $noticeM ->sendSMSType($msgData, $data['content']);
            
            $return['errcode']  =   $arr['status'] == '1' ? 9 : 8;
            $return['msg']      =   $arr['msg'];
               
            return $return;
        }
    }
    
    /**
     * @desc 客户管理，修改密码
     * @param array $data
     */
    function upPassword($data = array()) {
        
        $return =   array();
        
        $uid            =   intval($data['uid']);
        $pass           =   trim($data['password']);
        
        require_once 'userinfo.model.php';
        $userinfoM      =   new userinfo_model($this->db, $this->def);
        
        $passA          =   $userinfoM -> generatePwd(array('password'=>$pass));
        $password       =   $passA['pwd'];
        $salt           =   $passA['salt'];
        
        $return['id']   =   $this -> update_once('member',array('password'=>$password, 'salt'=>$salt), array('uid'=>$uid));
        
        if ($return['id']) {
            
            require_once 'sysmsg.model.php';
            
            $sysmsgM    =   new sysmsg_model($this->db, $this->def);
            
            $sysmsgM    ->  addInfo(array('uid' => $uid, 'usertype'=>2, 'content' => '管理员为您修改密码：'.$pass));
            
        }
        
        $return['errcode']  =   $return['id'] ? 9 : 8 ;
        
        $return['msg']      =   $return['id'] ? '密码修改成功！': '密码修改失败！' ;
        
        return $return;
    }
    /**
     * @desc 公众号通知业务员 crm
     * @desc $this -> MODEL('admin')->sendCrmWxMsg();
     */
    public function sendCrmWxMsg($auid='',$data=array('type'=>'','first'=>'','title'=>''))
    {
        if ($auid && $data['first']) {
            if($auid!='' && $auid>0){
                $awhere   =   array('uid' => $auid);
            }else{
                $awhere   =   array('m_id' => 1);
            }
            $user   =   $this->select_all('admin_user', $awhere, '`uid`,`name`,`moblie`,`r_status`,`wxid`');
            
            if (! empty($user)) {

                require_once ('weixin.model.php');
                $weixinM = new weixin_model($this->db, $this->def);

                foreach ($user as $v) {
                    if ($v['r_status'] == 1) {
                        
                        if ($v['wxid']) {
                            
                            $weixinM->sendWxAdmin(array(
                                'type'  => $data['type'],     
                                'first' => $data['first'],
                                'wxid'  => $v['wxid'],
                                'title' => $data['title'],
                            ));
                        }
                    }
                }
            }
        }
    }
    
    /**
     * @desc 我的客户数量查询: 客户总数，待审核客户，未通过客户，锁定客户
     * @param array $where
     * @return string
     */
    function getMyCustomerNum($data = array()){

        $crmUid =   intval($data['crm_uid']);
        $arr    =   array();
        //企业总数
        $companyAllNum					=	$this -> select_num('company', array('crm_uid' => $crmUid));
        if($companyAllNum > 0){
            $arr['companyAllNum']		=	$companyAllNum;
        }
        
        //待审核企业
        $companyStatusNum1				=	$this -> select_num('company',array('crm_uid' => $crmUid, 'r_status'=>'0'));
        if($companyStatusNum1 > 0){
            $arr['companyStatusNum1']	=	$companyStatusNum1;
        }
        
        //未通过企业
        $companyStatusNum2              =	$this -> select_num('company',array('crm_uid' => $crmUid, 'r_status'=>'3'));
        if($companyStatusNum2 > 0){
            $arr['companyStatusNum2']	=	$companyStatusNum2;
        }
        
        //锁定企业
        $companyStatusNum3              =	$this -> select_num('company',array('crm_uid' => $crmUid, 'r_status'=>'2'));
        if($companyStatusNum3 > 0){
            $arr['companyStatusNum3']	=	$companyStatusNum3;
        }
        return json_encode($arr);
    }
}
?>